package sixkey.controller;

/**
 * ClassName:PayController
 * Package:sixkey.controller
 * Description
 *
 * @Author:@wenxueshi
 * @Create:2023/6/26 - 22:42
 * @Version:v1.0
 */

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sixkey.config.AlipayConfig.AlipayConfig;
import sixkey.utils.ResResult;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 电脑网站支付
 */
@Slf4j
@Api(tags = "支付宝支付接口")
@RestController
@RequestMapping("/app")
@RequiredArgsConstructor
public class PayController {

    @RequestMapping(value = "index")
    public String payCoin(){
        return "index.html";
    }

    @ApiOperation(value = "支付接口")
    @RequestMapping("/pay")
    public String pay(@RequestParam("outTradeNo") String outTradeNo,@RequestParam("subject") String subject,@RequestParam("totalAmount") String totalAmount) throws AlipayApiException {
        // 实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.GATEWAY, AlipayConfig.APPID, AlipayConfig.APPPRIVATEKEY, "json", "utf-8", AlipayConfig.ALIPAYPUBLICKEY, "RSA2");
        // 实例化请求
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        // 设置异步通知地址
        alipayRequest.setNotifyUrl(AlipayConfig.NOTIFYURL);
        // 设置同步通知地址
        alipayRequest.setReturnUrl(AlipayConfig.RETURNURL);
        /*// 设置订单号
        String outTradeNo = "20230626112000001";
        // 设置订单总金额
        String totalAmount = "100.00";
        // 设置订单标题
        String subject = "测试电脑网站支付";*/
        // 组装请求参数
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(outTradeNo);
        model.setTotalAmount(totalAmount);
        model.setSubject(subject);
        model.setBody("测试电脑网站支付");
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        alipayRequest.setBizModel(model);
        // 请求支付宝进行支付
        String form = alipayClient.pageExecute(alipayRequest).getBody();
        return form;
    }

    @RequestMapping("/return_url")
    public String returnUrl(HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 解码
            params.put(name, URLDecoder.decode(valueStr, "UTF-8"));
        }
        // 验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAYPUBLICKEY, "UTF-8", "RSA2");
        if (signVerified) {
            // 获取订单号
            String outTradeNo = params.get("out_trade_no");
            // 获取支付宝交易号
            String tradeNo = params.get("trade_no");
            // 获取交易状态
            String tradeStatus = params.get("trade_status");
            if (tradeStatus.equals("TRADE_SUCCESS")) {
                // TODO: 处理业务逻辑
                return "success";
            }
        }
        return "fail";
    }

    @RequestMapping("/notify_url")
    public String notifyUrl(HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {
        // 获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 解码
            params.put(name, URLDecoder.decode(valueStr, "UTF-8"));
        }
        // 验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAYPUBLICKEY, "UTF-8", "RSA2");
        if (signVerified) {
            // 获取订单号
            String outTradeNo = params.get("out_trade_no");
            // 获取支付宝交易号
            String tradeNo = params.get("trade_no");
            // 获取交易状态
            String tradeStatus = params.get("trade_status");
            if (tradeStatus.equals("TRADE_SUCCESS")) {
                // TODO: 处理业务逻辑
                return "success";
            }
        }
        return "fail";
    }
}
